// pages/main-person-new/main-person.js
const app = getApp();
const _user = require("../../utils/User.js")
const api = require("../../server/Api.js");
const QR = require("../../utils/qrcode.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headUrl: "",
    userInfo: null, //用户信息
    isLogin: false,
    isStore: false,
    isFirst: true,
    count2: 0,
    count3: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let userBean = app.globalData.userBean;
    if (userBean && userBean.consumerId) {
      api.getStoresByUserId(userBean.consumerId).then((res) => {
        if (res.records.length > 0) {
          app.globalData.userShopId = res.records;
          that.setData({
            isStore: true
          })
        }
      }).catch(msg => {
        var message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // tt.showTabBar();
    let userBean = app.globalData.userBean;

    var isLogin = false;
    var headUrl = app.globalData.defaultHeadUrl;
    if (userBean && userBean.consumerId) {
      isLogin = true;
      headUrl = userBean.avatar || app.globalData.defaultHeadUrl;
    } else {
      isLogin = false;
    }
    this.setData({
      isLogin: isLogin,
      userInfo: userBean,
      headUrl: headUrl,
    })

    //如果没登陆，进行登录
    if (!isLogin && this.data.isFirst) {
      tt.stopPullDownRefresh();
      tt.navigateTo({
        url: '../login/login',
      })
    }

    this.setData({
      isFirst: false,
    })

    this.getUserQrCode();
    this.getOrderCount();
  },

  getUserQrCode() {
    let that = this;
    if (!that.data.isLogin) {
      return
    }
    let userBean = app.globalData.userBean;
    api.getUserCode(userBean.consumerId).then(res => {
      QR.api.draw(res, "mycanvas", 245 * app.globalData.rpxToPxBl, 245 * app.globalData.rpxToPxBl);
    }).catch(msg => {
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  getOrderCount() {
    let that = this;
    that.setData({
      count2: 0,
      count3: 0
    })
    if (!that.data.isLogin) {
      app.globalData.cartCount = 0;
      app.setTabBarBadge();
      return
    }
    this.queryOrderCount(2, count => {
      that.setData({
        count2: count
      })
    })
    this.queryOrderCount(3, count => {
      that.setData({
        count3: count
      })
    })
    this.queryAllOrderCount()
  },

  queryOrderCount(status, callback) {
    let that = this;
    let userBean = app.globalData.userBean;
    let prams = {
      pageSize: 1,
      pageNumber: 1,
      userId: userBean.consumerId,
      status: status
    };
    api.queryOrderList(prams).then(res => {
      callback(res.total)
    })
  },

  queryAllOrderCount() {
    let that = this;
    let userBean = app.globalData.userBean;
    let prams = {
      pageSize: 100,
      pageNumber: 1,
      platformId: app.globalData.platformId,
      userId: userBean.consumerId
    };
    api.queryCartList(prams).then(res => {
      let total = 0;
      for (let i = 0; i < res.records.length; i++) {
        for (let j = 0; j < res.records[i].cartVO.length; j++) {
          res.records[i].cartVO[j].skuImage = app.resetImageUrl(res.records[i].cartVO[j].skuImage, 172, 172);
          total += parseInt(res.records[i].cartVO[j].goodsQuantity)
        }
      }
      app.globalData.cartCount = total;
      app.setTabBarBadge();
    })
  },

  //前往地址管理
  toAddress: function(e) {
    _user.startPage('../setting-my-address/setting-my-address');
  },
  changeUser: function(e) {
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
      return
    }
    let that = this;
    tt.showModal({
      title: '切换账号',
      content: '',
      success: function(e) {
        if (e.confirm) {
          _user.exit()
          app.globalData.userBean = null;
          app.globalData.userInfo = null;
          that.toLogin();
        }
      }
    })
  },
  toLogin: function(e) {
    tt.navigateTo({
      url: '../login/login',
    })
  },
  toChangeUser: function() {
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
      return
    }
    tt.hideTabBar({
      success: function() {
        tt.navigateTo({
          url: '../shop-user-index/index',
          success() {
            app.showToast("切换成功");
          }
        })
      }
    })
  },
  toCoupons: function() {
    app.showToast("功能未开放")
    // tt.navigateTo({
    //   url: '../coupons/coupons',
    // })
  },
  toShopInfo: function() {
    tt.navigateTo({
      url: '../shop-info/shop-info',
    })
  },
  makePhone: function() {
    const that = this;
    if (app.globalData.shopId && app.globalData.shopId != "") {
      api.getShopInfo(app.globalData.shopId).then(res => {
        console.log("店铺信息:", res);
        tt.makePhoneCall({
          phoneNumber: res.mobile
        })
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    } else {
      app.showToast("正在定位店铺,请稍后再试!");
    }
  },
  tapAvatar() {
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
      return
    }
    // tt.chooseImage({
    //   count: 1,
    //   success: function(res) {
    //     console.log(res.tempFiles[0])
    //   }
    // })
  },
  toHelp() {
    tt.navigateTo({
      url: '../../help/index',
    })
  }
})